<?php
class PerfsonarNCSoap {

	var $socket,$socketname;

	function PerfsonarNCSoap() {
		require("perfsonarnc.cfg.php");
		//Connect to server
		if (($this->socket=pfsockopen("unix://".$cfg['socket'])) === false)
		die("pfsockopen() failed\n");
		if(ftell($this->socket)>0) {
			fclose($this->socket);
			if (($this->socket=pfsockopen("unix://".$cfg['socket'])) === false)
				die("pfsockopen() failed\n");			
		}			
	}

	function hello($hello) {
		$xml="";
		while($str=rtrim(fgets($this->socket)))
	 		if($str=="]]>]]>")
				break;
			else
				$xml.=$str;

		$ret = array (
                 'capabilities' => array (
                                           'urn:ietf:params:netconf:base:1.0',
                                           'urn:ietf:params:netconf:xpath:1.0',
					   'urn:ietf:params:netconf:writable-running:1.0'
					   ),
                  'session-id' => 1);
					   $str='<?xml version="1.0"?>
<hello xmlns="urn:ietf:params:xml:ns:netconf:base:1.0"><capabilities>';
					   foreach($hello->capabilities->capability as $capability)
					   $str.="<capability>$capability</capability>";
					   $str.="</capabilities></hello>\n]]>]]>\n";
					   fputs($this->socket,$str);
					   return $ret;
	}

	public function __wakeup() {
		require("perfsonarnc.cfg.php");
		//Connect to server
		if (($this->socket=pfsockopen("unix://".$cfg['socket'])) === false)
		die("pfsockopen() failed\n");
	}

	function rpc($rpc) {
		$arr=(array)$rpc;
		if(isset($rpc->get))
		if(isset($rpc->get->filter))
		if($rpc->get->filter->type=="xpath") {
			$str="<?xml version='1.0'?><rpc xmlns='urn:ietf:params:xml:ns:netconf:base:1.0' message-id='".$arr['message-id']."'><get><source><running/></source><filter type='xpath' select=\"".$rpc->get->filter->select."\"/></get></rpc>\n]]>]]>\n";
			fputs($this->socket,$str);
			$xml="";
			while(true) {
				$str=rtrim(fgets($this->socket));
				if($str=="]]>]]>") {
					$str="";
					if(strlen($xml)>0)
						break;
				}
				else
					$xml.=$str;
			}
			return new SoapVar(substr($xml, (strpos($xml, ">")+1)),XSD_ANYXML);
		}
		if(isset($arr['edit-config'])) {
			$editxml='<?xml version="1.0" encoding="UTF-8"?><rpc xmlns="urn:ietf:params:xml:ns:netconf:base:1.0" message-id="1"><edit-config><target><running/></target><config>'.
					$arr['edit-config']->config->_."</config></edit-config></rpc>";
			fputs($this->socket,$editxml."\n]]>]]>\n");
			$xml="";
			while(true) {
				$str=rtrim(fgets($this->socket));
				if($str=="]]>]]>") {
					$str="";
					if(strlen($xml)>0)
						break;
				}
				else
					$xml.=$str;
			}
			return new SoapVar(substr($xml, (strpos($xml, ">")+1)),XSD_ANYXML);
		}
	}
}


session_start();
$server = new SoapServer("perfsonarnc.wsdl");
$server->setClass("PerfsonarNCSoap");
$server->setPersistence(SOAP_PERSISTENCE_SESSION);
$server->handle();

?>